package com.imooc.coupon.service.impl;

import com.imooc.coupon.entity.CouponTemplate;
import com.imooc.coupon.service.ITemplateBaseService;
import com.imooc.coupon.dao.CouponTemplateDao;
import com.imooc.coupon.exception.CouponException;
import com.imooc.coupon.vo.CouponTemplateSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author Administrator
 * @Date 2021/10/24 20:50
 * @Version 1.0
 */
@Service
public class TemplateBaseServiceImpl implements ITemplateBaseService {

    @Autowired
    private CouponTemplateDao templateDao;

    @Override
    public CouponTemplate buildTemplateInfo(Integer id) throws CouponException {
        Optional<CouponTemplate> template = templateDao.findById(id);
        if (!template.isPresent()) {
            throw new CouponException("Template Is Not Exists!");
        }
        return template.get();
    }

    @Override
    public List<CouponTemplateSDK> findAllUsAbleTemplate() throws CouponException {
        List<CouponTemplate> templates =
                templateDao.findAllByAvailableAndExpired(true, false);
        return templates.stream().map(this::template2CouponTemplateSDK)
                .collect(Collectors.toList());
    }

    @Override
    public Map<Integer, CouponTemplateSDK> findIds2CopontemplateSDK(Collection<Integer> ids) {
        List<CouponTemplate> templates = templateDao.findAllById(ids);
        return templates.stream().map(this::template2CouponTemplateSDK)
                .collect(Collectors.toMap(CouponTemplateSDK::getId, Function.identity()));

    }

    private CouponTemplateSDK template2CouponTemplateSDK(CouponTemplate template) {
        return new CouponTemplateSDK(
                template.getId(),
                template.getName(),
                template.getLogo(),
                template.getDesc(),
                template.getCategory().getCode(),
                template.getProductLine().getCode(),
                template.getKey(),
                template.getTarget().getCode(),
                template.getRule());
    }
}
